package com.example.kafka.producer;

import org.apache.kafka.clients.producer.*;
import org.apache.kafka.common.serialization.StringSerializer;

import java.util.Properties;

/**
 * 异步发送消息
 * 带回调
 * 分区测试:
 *  1.指定partition进行分区
 *  2.根据key的hash值，与partition的个数取模运算进行分区
 *  3.粘性分区，随机分配到一个分区，等到一个batch.size满足（16k）或者linger.ms时间满足，则从剩余的分区中进行随机选择分配
 */
public class CustomProducerCallbackPartitions {
    public static void main(String[] args) {

        // 0.创建properties
        Properties properties = new Properties();
        // 连接集群 bootstrap.servers
//        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "server1:9092,server2:9092");
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
        // 指定对应的key和value的序列化类型 key.serializer
//        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName()); // 和上面的写法等价
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());

        // 关联自定义分区器
        properties.put(ProducerConfig.PARTITIONER_CLASS_CONFIG, MyPartitioner.class.getName());

        // 1.创建kafka生产者对象
        KafkaProducer<String, String> kafkaProducer = new KafkaProducer<String, String>(properties);
        // 2.发送消息
        for (int i = 0; i < 5; i++) {
            kafkaProducer.send(new ProducerRecord<String, String>("test", 0,"","hello kafka" + i), new Callback() {
                public void onCompletion(RecordMetadata recordMetadata, Exception e) {
                    System.out.println("主题：" + recordMetadata.topic() + ", 分区：" + recordMetadata.partition());
                    System.out.println("是否有偏移：" + recordMetadata.hasOffset() + ", 偏移：" + recordMetadata.offset());
                }
            });
        }

        // 3.关闭资源
        kafkaProducer.close();
    }
}
